using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;

using HorrorsOfArkham.Game_Application_Layer;

namespace HorrorsOfArkham
{
#if WINDOWS

    internal static class Program
    {
        #region Members

        private static readonly HandleRef _handleRef = default(HandleRef);

        private static readonly string uniqueGameAppID = "HorrorsOfArkham";

        private static readonly string WINDOW_TITLE = "Horrors Of Arkham";

        #endregion

        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool PeekMessage(out NativeMessage lpMsg, HandleRef hWnd, uint wMsgFilterMin, uint wMsgFilterMax, uint wRemoveMsg);

        #region Main

        [STAThread]
        static void Main()
        {
            bool initDone = HorrorsGameAppHandler.Instance.InitInstance(uniqueGameAppID);

            if (!initDone)
            {
                Console.WriteLine("Game initialization failed!");

                QuickShutDown();

            }

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(true);

            var gameForm = new GameForm();
            gameForm.Text = WINDOW_TITLE;

            Application.Idle += (sender, args) => ApplicationOnIdle(gameForm);
            Application.Run(gameForm);
        }

        #endregion


        #region Message Pump

        private static void ApplicationOnIdle(GameForm gameForm)
        {
            NativeMessage message;

            while (!PeekMessage(out message, _handleRef, 0, 0, 0))
            {
                gameForm.Render();
            }
        }

        [StructLayout(LayoutKind.Sequential)]
        private struct NativeMessage
        {
            private readonly IntPtr handle;
            private readonly uint msg;
            private readonly IntPtr wParam;
            private readonly IntPtr lParam;
            private readonly uint time;
            private readonly Point p;
        }

        #endregion

        #region Shutdown

        private static void QuickShutDown()
        {
            Console.WriteLine("Shutting Down");
            System.Environment.Exit(0);
        }

        #endregion
    }

#endif
}

